import { Component } from '../core/Component.js';

/**
 * 线性布局组件
 */
export class LinearLayout extends Component {
  constructor(props = {}) {
    super(props);
    this.orientation = props.orientation || 'vertical';
    this.children = [];
    this.style = props.style || {};
  }

  addChild(component) {
    this.children.push(component);
    // 传递主题给子组件
    if (this.theme) {
      component.theme = this.theme;
    }
    if (this.element && component.render) {
      this.element.appendChild(component.render());
    }
  }

  /**
   * 重写update方法，避免重新创建DOM元素
   */
  update() {
    // 不重新创建DOM元素，只重新应用样式
    if (this.element) {
      this.applyStyle();
    }
  }

  applyStyle() {
    if (!this.element) return;
    
    // 基础样式
    this.element.style.display = 'flex';
    this.element.style.flexDirection = this.orientation === 'horizontal' ? 'row' : 'column';
    this.element.style.gap = '10px';
    this.element.style.transition = 'background-color 0.3s ease';
    
    // 主题样式
    if (this.theme && this.theme.mode) {
      // LinearLayout通常不需要背景色，让它透明
      this.element.style.backgroundColor = 'transparent';
    }
    
    // 自定义样式（最后应用，可以覆盖主题样式）
    for (const [key, value] of Object.entries(this.style)) {
      this.element.style[key] = value;
    }
    
    // 更新所有子组件的主题
    this.children.forEach(child => {
      if (this.theme) {
        child.theme = this.theme;
        if (child.applyStyle) {
          child.applyStyle();
        }
      }
    });
  }

  render() {
    this.element = document.createElement('div');
    this.applyStyle();
    
    this.children.forEach(child => {
      if (child.render) {
        const childElement = child.render();
        if (childElement) {
          this.element.appendChild(childElement);
        }
      }
    });

    return this.element;
  }
}